﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Web.Hosting;
using Amba.System.Extensions;
using Amba.ULogin.Models;
using Microsoft.SqlServer.Server;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Environment.Configuration;
using Orchard.Logging;
using Orchard.Security;
using Orchard.Users.Models;

namespace Amba.ULogin.Services
{
    public interface IUserToolsService : IDependency
    {
        string GetUserPrettyName(string userName);
        string GetUserPrettyName(IContent userContentItem);

        string GetUserPic(string userName, string defaultImage);

        string SaveUserPic(string userName, string picUrl, string imageType = "small");
    }

    public class UserToolsService : IUserToolsService
    {
        private readonly IMembershipService _membershipService;
        private readonly string _userPicsMediaFolder;
        public ILogger Logger { get; set; }

        public string UserPicsFolder
        {
            get { return _userPicsMediaFolder; }
        }


        public UserToolsService(IMembershipService membershipService, ShellSettings shellSettings)
        {
            _membershipService = membershipService;
            Logger = NullLogger.Instance;
            _userPicsMediaFolder = "/Media/" + shellSettings.Name + "/Users";
           
        }

        string GetServerPath(string path)
        {
            path = path.RegexRemove(@"^~/").TrimStart('/');
            return HostingEnvironment.IsHosted
                                ? HostingEnvironment.MapPath("~/" + path) ?? ""
                                : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
        }

        public string SaveUserPic(string username, string picUrl, string imageType = "small")
        {
            if (string.IsNullOrWhiteSpace(picUrl) || !picUrl.Trim().ToLower().IsMatch("^http"))
                return picUrl;

            picUrl = picUrl.Trim();
            try
            {
                var folderServerPath = GetServerPath(_userPicsMediaFolder);
                if (!Directory.Exists(folderServerPath))
                {
                    Directory.CreateDirectory(folderServerPath);
                }
                var webClient = new WebClient();
                var extension = picUrl.RegexMatchOne(@"\.(\w)^");
                if (string.IsNullOrWhiteSpace(extension))
                    extension = "jpg";
                var fileName = _userPicsMediaFolder + @"/" + username + "_" + imageType + "." + extension;
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                webClient.DownloadFile(picUrl, GetServerPath(fileName));
                return fileName;
            }
            catch (Exception e)
            {
                Logger.Error(e, "Cannot dowload image");
                return picUrl;
            }
        }

        public string GetUserPrettyName(string userName)
        {
            var user = _membershipService.GetUser(userName);
            if (user == null)
                return userName;
            
            return GetUserPrettyName(user.ContentItem);
        }

        private string GetFirstName(IContent userContentItem)
        {
            var userData = userContentItem.As<ULoginUserDataPart>();
            if (userData != null && !string.IsNullOrWhiteSpace(userData.FirstName))
                return userData.FirstName;
            var userContent = (dynamic)userContentItem;
            if (HasFields(userContentItem) && userContent.User.FirstName != null)
                return userContent.User.FirstName.Value;
            return string.Empty;
        }

        private bool HasFields(IContent content)
        {
            return content.ContentItem.Parts.Any(x => x.PartDefinition.Name == "User");           
        }

        private string GetLastName(IContent userContentItem)
        {
            var userData = userContentItem.As<ULoginUserDataPart>();
            if (userData != null && !string.IsNullOrWhiteSpace(userData.LastName))
                return userData.LastName;
            var userContent = (dynamic)userContentItem;
            if (HasFields(userContentItem) && userContent.User.LastName != null)
                return userContent.User.LastName.Value;
            return string.Empty;
        }
        private string GetPhoto(IContent userContentItem)
        {
            var userData = userContentItem.As<ULoginUserDataPart>();
            if (userData != null && !string.IsNullOrWhiteSpace(userData.Photo))
                return userData.Photo;
            var userContent = (dynamic)userContentItem;
            if (HasFields(userContentItem) && userContent.User.photo != null)
                return userContent.User.photo.Value;
            return string.Empty;
        }

        private string GetPhotoBig(IContent userContentItem)
        {
            var userData = userContentItem.As<ULoginUserDataPart>();
            if (userData != null && !string.IsNullOrWhiteSpace(userData.PhotoBig))
                return userData.PhotoBig;
            var userContent = (dynamic)userContentItem;
            if (HasFields(userContentItem) && userContent.User.photobig != null)
                return userContent.User.photobig.Value;
            return string.Empty;
        }

        public string GetUserPrettyName(IContent userContentItem)
        {
            string prettyName = GetFirstName(userContentItem) + " " + GetLastName(userContentItem);
            prettyName = prettyName.Trim();
            if (string.IsNullOrWhiteSpace(prettyName))
                return userContentItem.As<UserPart>().UserName;
            return prettyName;
        }

        public string GetUserPic(string userName, string defaultImage)
        {
            var user = _membershipService.GetUser(userName);
            if (user == null)
                return defaultImage;
            var photo = GetPhotoBig(user);
            if (!string.IsNullOrWhiteSpace(photo))
                return photo;

            photo = GetPhoto(user);
            if (string.IsNullOrWhiteSpace(photo))
            {
                return defaultImage;
            }
            return photo;
        }
    }
}